import React, { FC, memo, useMemo, useState } from 'react';
import SvgIcon from '@/components/svg-icon/SvgIcon';
import { Dropdown, Menu } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { HandleOrder, OrderOptions } from '@/types/OrderOptions';
import { MenuInfo } from 'rc-menu/es/interface';

interface IOrderDropDownBaseProps {
  orderOptions: OrderOptions[];
  handleOrder?: HandleOrder;
  defaultOrderKey?: string;
  hasIcon?: boolean;
  labelMinWidth?: string;
}

const OrderDropDownBase: FC<IOrderDropDownBaseProps> = (props) => {
  const { orderOptions, handleOrder, defaultOrderKey, hasIcon, labelMinWidth } =
    props;
  const _hasIcon = hasIcon === false ? false : true;

  const [orderKey, setOrderKey] = useState(defaultOrderKey || '');
  const [orderType, setOrderType] = useState('');

  const onMenuClick = (info: MenuInfo) => {
    const key = info.key;
    setOrderKey(key);
    handleOrder && handleOrder(`${key} ${orderType}`, key, orderType);
  };

  const menu = useMemo(() => {
    return (
      <Menu onClick={onMenuClick}>
        {orderOptions.map((option) => (
          <Menu.Item
            disabled={option.value === orderKey}
            key={`${option.value}`}
          >
            {option.text}
          </Menu.Item>
        ))}
      </Menu>
    );
  }, [orderKey, onMenuClick]);

  const orderIconClazz = useMemo(() => {
    if (!orderType) {
      return `icon-shangxia-copy`;
    }
    if (orderType === 'asc') {
      return `icon-xiangxia`;
    }
    if (orderType === `desc`) {
      return `icon-xiangshang`;
    }
    return '';
  }, [orderType]);

  const changeOrderType = () => {
    const newOrderType = orderType
      ? orderType === 'asc'
        ? 'desc'
        : ''
      : 'asc';
    setOrderType((orderType) => newOrderType);
    handleOrder &&
      handleOrder(`${orderKey} ${newOrderType}`, orderKey, newOrderType);
  };
  const minerOrderTranslate = (key: string) => {
    return orderOptions.find((option) => option.value === key)?.text;
  };

  return (
    <div className="flex ai-center">
      {_hasIcon ? (
        <SvgIcon
          symbol={orderIconClazz}
          onClick={() => changeOrderType()}
          style={{ marginRight: '6px', cursor: 'pointer' }}
        />
      ) : null}

      <Dropdown overlay={menu} trigger={['click']} placement="bottomCenter">
        <a>
          <span
            style={{
              minWidth: labelMinWidth || '65px',
              display: 'inline-block',
            }}
          >
            {minerOrderTranslate(orderKey)}
          </span>

          <DownOutlined style={{ marginLeft: '6px' }} />
        </a>
      </Dropdown>
    </div>
  );
};

export default memo(OrderDropDownBase);
